import { TaskManager } from '../../utils/taskManager.js'

Page({
  data: {
    allTasks: [], // 所有任务
    loading: false, // 加载状态
    searchKeyword: '', // 搜索关键词
    showSearch: false, // 是否显示搜索栏
    filteredTasks: [], // 筛选后的任务列表
    filterType: 'all', // 筛选类型：all, completed, pending
    sortType: 'createTime_desc', // 排序类型
    sortOptions: [
      { value: 'createTime_desc', label: '创建时间↓' },
      { value: 'createTime_asc', label: '创建时间↑' },
      { value: 'updateTime_desc', label: '更新时间↓' },
      { value: 'completeTime_desc', label: '完成时间↓' },
      { value: 'priority_asc', label: '优先级↑' },
      { value: 'title_asc', label: '标题A-Z' }
    ],
    stats: {
      total: 0,
      completed: 0,
      pending: 0,
      completionRate: 0
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    console.log('历史记录页面加载')
    this.loadHistoryData()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadHistoryData()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadHistoryData()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },

  /**
   * 加载历史数据
   */
  loadHistoryData() {
    this.setData({ loading: true })
    
    try {
      const allTasks = TaskManager.getAllTasks()
      
      // 处理任务数据
      const processedTasks = allTasks.map(task => ({
        ...task,
        formattedCreateTime: this.formatTime(task.createTime),
        formattedUpdateTime: this.formatTime(task.updateTime),
        formattedCompleteTime: task.completeTime ? this.formatTime(task.completeTime) : null,
        priorityInfo: this.getPriorityInfo(task.priority),
        statusText: this.getStatusText(task.status)
      }))
      
      // 计算统计信息
      const stats = this.calculateStats(allTasks)
      
      this.setData({
        allTasks: processedTasks,
        stats: stats,
        loading: false
      })
      
      // 应用筛选和排序
      this.applyFiltersAndSort()
      
      console.log('历史数据加载成功:', processedTasks.length)
    } catch (error) {
      console.error('加载历史数据失败:', error)
      this.setData({ loading: false })
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      })
    }
  },

  /**
   * 计算统计信息
   */
  calculateStats(tasks) {
    const total = tasks.length
    const completed = tasks.filter(task => task.status === 1).length
    const pending = tasks.filter(task => task.status === 0).length
    const completionRate = total > 0 ? Math.round((completed / total) * 100) : 0
    
    return {
      total,
      completed,
      pending,
      completionRate
    }
  },

  /**
   * 应用筛选和排序
   */
  applyFiltersAndSort() {
    let filteredTasks = [...this.data.allTasks]
    
    // 应用状态筛选
    if (this.data.filterType !== 'all') {
      const statusFilter = this.data.filterType === 'completed' ? 1 : 0
      filteredTasks = filteredTasks.filter(task => task.status === statusFilter)
    }
    
    // 应用搜索筛选
    if (this.data.searchKeyword.trim()) {
      const keyword = this.data.searchKeyword.trim().toLowerCase()
      filteredTasks = filteredTasks.filter(task => 
        task.title.toLowerCase().includes(keyword) ||
        (task.note && task.note.toLowerCase().includes(keyword))
      )
    }
    
    // 应用排序
    filteredTasks = this.applySorting(filteredTasks)
    
    this.setData({ filteredTasks })
  },

  /**
   * 应用排序
   */
  applySorting(tasks) {
    const [field, order] = this.data.sortType.split('_')
    
    return [...tasks].sort((a, b) => {
      let aValue, bValue
      
      switch (field) {
        case 'createTime':
        case 'updateTime':
          aValue = a[field] || 0
          bValue = b[field] || 0
          break
        case 'completeTime':
          aValue = a[field] || 0
          bValue = b[field] || 0
          // 未完成的任务排在后面
          if (aValue === 0 && bValue === 0) return 0
          if (aValue === 0) return 1
          if (bValue === 0) return -1
          break
        case 'priority':
          aValue = a.priority
          bValue = b.priority
          break
        case 'title':
          aValue = a.title.toLowerCase()
          bValue = b.title.toLowerCase()
          break
        default:
          return 0
      }
      
      if (order === 'asc') {
        return aValue > bValue ? 1 : aValue < bValue ? -1 : 0
      } else {
        return aValue < bValue ? 1 : aValue > bValue ? -1 : 0
      }
    })
  },

  /**
   * 获取优先级信息
   */
  getPriorityInfo(priority) {
    const priorityMap = {
      1: { text: '高', color: '#ff4757' },
      2: { text: '中', color: '#ffa502' },
      3: { text: '低', color: '#2ed573' }
    }
    return priorityMap[priority] || priorityMap[2]
  },

  /**
   * 获取状态文本
   */
  getStatusText(status) {
    const statusMap = {
      0: '待完成',
      1: '已完成',
      2: '已删除'
    }
    return statusMap[status] || '未知'
  },

  /**
   * 格式化时间
   */
  formatTime(timestamp) {
    const date = new Date(timestamp)
    return date.getFullYear() + '/' + 
           (date.getMonth() + 1).toString().padStart(2, '0') + '/' + 
           date.getDate().toString().padStart(2, '0') + ' ' +
           date.getHours().toString().padStart(2, '0') + ':' + 
           date.getMinutes().toString().padStart(2, '0')
  },

  /**
   * 切换搜索栏显示
   */
  toggleSearch() {
    const showSearch = !this.data.showSearch
    this.setData({
      showSearch: showSearch
    })
    
    if (!showSearch) {
      this.setData({ searchKeyword: '' })
      this.applyFiltersAndSort()
    }
  },

  /**
   * 搜索输入
   */
  onSearchInput(e) {
    const keyword = e.detail.value
    this.setData({ searchKeyword: keyword })
    this.applyFiltersAndSort()
  },

  /**
   * 清空搜索
   */
  clearSearch() {
    this.setData({ searchKeyword: '' })
    this.applyFiltersAndSort()
  },

  /**
   * 筛选类型改变
   */
  onFilterChange(e) {
    const filterType = e.currentTarget.dataset.type
    this.setData({ filterType: filterType })
    this.applyFiltersAndSort()
    
    const filterMap = {
      all: '全部',
      completed: '已完成',
      pending: '待完成'
    }
    
    wx.showToast({
      title: `筛选：${filterMap[filterType]}`,
      icon: 'none',
      duration: 1000
    })
  },

  /**
   * 排序方式改变
   */
  onSortChange(e) {
    const sortIndex = e.detail.value
    const sortType = this.data.sortOptions[sortIndex].value
    
    this.setData({ sortType: sortType })
    this.applyFiltersAndSort()
    
    const sortLabel = this.data.sortOptions[sortIndex].label
    wx.showToast({
      title: `按${sortLabel}排序`,
      icon: 'none',
      duration: 1000
    })
  },

  /**
   * 点击任务项
   */
  onTaskTap(e) {
    const taskId = e.currentTarget.dataset.id
    console.log('查看任务详情:', taskId)
    
    // 跳转到任务详情页
    wx.navigateTo({
      url: `/pages/detail/detail?id=${taskId}`
    })
  },

  /**
   * 长按任务项
   */
  onTaskLongTap(e) {
    const taskId = e.currentTarget.dataset.id
    const task = this.data.filteredTasks.find(t => t.id === taskId)
    
    if (!task) return
    
    const actionList = ['查看详情']
    
    if (task.status === 0) {
      actionList.push('标记完成')
    } else if (task.status === 1) {
      actionList.push('恢复为待完成')
    }
    
    actionList.push('删除任务')
    
    wx.showActionSheet({
      itemList: actionList,
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            this.viewTaskDetail(task)
            break
          case 1:
            if (task.status === 0) {
              this.completeTask(task)
            } else if (task.status === 1) {
              this.restoreTask(task)
            }
            break
          case 2:
            this.deleteTask(task)
            break
        }
      }
    })
  },

  /**
   * 查看任务详情
   */
  viewTaskDetail(task) {
    wx.navigateTo({
      url: `/pages/detail/detail?id=${task.id}`
    })
  },

  /**
   * 完成任务
   */
  completeTask(task) {
    wx.showLoading({ title: '处理中...' })
    
    const result = TaskManager.completeTask(task.id)
    wx.hideLoading()
    
    if (result.success) {
      wx.showToast({
        title: result.message,
        icon: 'success'
      })
      
      this.loadHistoryData()
      wx.vibrateShort()
    } else {
      wx.showToast({
        title: result.message,
        icon: 'error'
      })
    }
  },

  /**
   * 恢复任务
   */
  restoreTask(task) {
    wx.showLoading({ title: '处理中...' })
    
    const result = TaskManager.uncompleteTask(task.id)
    wx.hideLoading()
    
    if (result.success) {
      wx.showToast({
        title: result.message,
        icon: 'success'
      })
      
      this.loadHistoryData()
      wx.vibrateShort()
    } else {
      wx.showToast({
        title: result.message,
        icon: 'error'
      })
    }
  },

  /**
   * 删除任务
   */
  deleteTask(task) {
    wx.showModal({
      title: '确认删除',
      content: `确定要删除任务"${task.title}"吗？此操作不可恢复！`,
      confirmText: '删除',
      confirmColor: '#ff4757',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' })
          
          const result = TaskManager.deleteTask(task.id)
          wx.hideLoading()
          
          if (result.success) {
            wx.showToast({
              title: result.message,
              icon: 'success'
            })
            
            this.loadHistoryData()
          } else {
            wx.showToast({
              title: result.message,
              icon: 'error'
            })
          }
        }
      }
    })
  },

  /**
   * 导出历史数据
   */
  exportHistory() {
    try {
      const exportData = {
        tasks: this.data.allTasks,
        stats: this.data.stats,
        exportTime: new Date().toISOString(),
        version: '1.0.0'
      }
      
      const jsonString = JSON.stringify(exportData, null, 2)
      
      wx.showModal({
        title: '导出历史数据',
        content: `导出 ${this.data.allTasks.length} 个任务的历史数据`,
        showCancel: true,
        confirmText: '确定',
        success: (res) => {
          if (res.confirm) {
            wx.showToast({
              title: '数据导出成功',
              icon: 'success'
            })
          }
        }
      })
    } catch (error) {
      console.error('导出历史数据失败:', error)
      wx.showToast({
        title: '导出失败',
        icon: 'error'
      })
    }
  }
}) 